package org.jaaksi.client;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import org.jaaksi.svc.IEncryption;
import org.jaaksi.svcmanager.ServiceManager;

public class MainActivity extends AppCompatActivity {
  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    testSvcManager();
  }

  private void test(IBinder service) {
    System.out.println("client binder = " + service);
    IEncryption decoder = IEncryption.Stub.asInterface(service);
    System.out.println("client IDecoder = " + decoder);
    try {
      String decode = decoder.encrypt("I love you");
      System.out.println("decode = " + decode);
    } catch (RemoteException e) {
      e.printStackTrace();
    }
  }

  private void testSvcManager() {
    // server addService
    IBinder binder = ServiceManager.getService(this, "xixi", "org.jaaksi.server");
    test(binder);
  }

  private void testService() {
    Intent intent = new Intent("action.service.binder");
    intent.setPackage("org.jaaksi.server");
    bindService(intent, new ServiceConnection() {
      /**
       * @param name
       * @param service android系统传输binder（可以认为是个管道）（并不是同一对象）
       */
      @Override
      public void onServiceConnected(ComponentName name, IBinder service) {
        test(service);
      }

      @Override
      public void onServiceDisconnected(ComponentName name) {

      }
    }, Context.BIND_AUTO_CREATE);
  }

  /*public class EncryptionService extends Service {
    private EncryptionImpl decoder = new EncryptionImpl();

    @Override
    public void onCreate() {
      super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
      return decoder;
    }
  }*/
}
